﻿using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using SaveFileDialog = Microsoft.Win32.SaveFileDialog;

namespace AdvanceScreening
{
    public partial class MainWindow : Window
    {
        private readonly ViewModel _viewModel = new ViewModel();

        private CancellationTokenSource _recordCancellationTokenSource;

        [DllImport("User32.dll")]
        static extern IntPtr WindowFromPoint(POINT p);

        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;

            public POINT(int x, int y)
            {
                X = x;
                Y = y;
            }

            public POINT(System.Drawing.Point pt) : this(pt.X, pt.Y) { }

            public static implicit operator System.Drawing.Point(POINT p)
            {
                return new System.Drawing.Point(p.X, p.Y);
            }

            public static implicit operator POINT(System.Drawing.Point p)
            {
                return new POINT(p.X, p.Y);
            }
        } 

        public MainWindow()
        {
            InitializeComponent();
            DataContext = _viewModel;
        }

        private async void RecordButtonOnClick(object sender, RoutedEventArgs e)
        {
            _viewModel.IsRecording = true;

            var dialog = new SaveFileDialog
            {
                FileName = _viewModel.SelectedCaptureRegion.Name + ".avi",
                Filter = "Video Files|*.avi"
            };

            bool? result = dialog.ShowDialog();
            if (result != null && result.Value)
            {
                var handle = _viewModel.SelectedCaptureRegion.MainWindowHandle;

                _recordCancellationTokenSource = new CancellationTokenSource();

                var capture = new Capture();
                await capture.Start(dialog.FileName, handle, _recordCancellationTokenSource.Token);
            }

            _viewModel.IsRecording = false;
        }

        private void StopButtonOnClick(object sender, RoutedEventArgs e)
        {
            _recordCancellationTokenSource.Cancel();

            _viewModel.IsRecording = false;
        }

        private void SelectButtonOnClick(object sender, RoutedEventArgs e)
        {
            MouseHook.Start();
            MouseHook.MouseAction += (o, args) =>
            {
                var window = WindowFromPoint(new POINT(args.X, args.Y));
                _viewModel.SelectedCaptureRegion = new CaptureRegion("Window", window);

                MouseHook.Stop();
            };
        }

        private void ScreenButtonOnClick(object sender, RoutedEventArgs e)
        {
            _viewModel.SelectedCaptureRegion = ViewModel.ScreenRegion;
        }
    }
}